package login.web;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author Administrator
 * @Date 2020/6/4 15:48
 **/
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*1、创建一个图片对象
          2、使用画笔Graphics
             1)填充背景颜色
             2）画边框
             3）写字符（随即产生）
             4）画干扰线
           3、将图片输出到页面显示 ImageIO
         */
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        /*2、使用画笔功能去美化图片*/
        Graphics g = image.getGraphics();
        /*设置颜色*/
        g.setColor(Color.GRAY);
        /*填充背景颜色*/
        g.fillRect(0,0,width,height);
        /*画边框*/
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);
        /*产生4个随即字符*/
        String s="qwertyuiopasdfghjklzxcvbnm0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
        Random random = new Random();
        /*sb用于存储产生的4个随即字符*/
        StringBuilder sb=new StringBuilder();
        for (int i=0;i<4;i++){
            /*产生随机索引*/
          int index=random.nextInt(s.length());
          /*根据索引得到随机字符*/
            char ch = s.charAt(index);
            /*保存随机字符*/
            sb.append(ch);
        }
        /*将验证码字符串保存在session域对象*/
        request.getSession().setAttribute("session_code",sb.toString());
        g.setColor(Color.YELLOW);
        /*设置字体*/
        g.setFont( new Font("黑体",Font.BOLD,18));
        g.drawString(sb.toString(),18,20);
        /*3、将图片输出到页面显示*/
        ImageIO.write(image,"jpg",response.getOutputStream());




    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
